package com.scf.auth.controller;


import com.alibaba.fastjson.JSON;
import com.scf.entity.RoleMenu;
import com.scf.entity.User;
import com.scf.service.UserService;
import com.scf.uitl.JwtUtil;
import com.scf.uitl.ResponseResult;
import com.scf.uitl.ResultStatus;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author author
 * @create 2021-10-26-15:10
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private UserService userService;

    //认证方法
    @PostMapping("/login")
    private ResponseResult auth(@RequestBody User user, HttpServletResponse response){
        //1.逻辑，通过账号查找账号信息，比对密码  引入MD5加密工具
        User getUser = userService.getUser(user);
        //假设验证成功
        //1.生成token，refreshToken
        if(getUser!=null) {
            List<RoleMenu> roleMenu = getUser.getRole().getRoleMenu();
            String token = JwtUtil.generateToken(user.getUname());
            String refreshToken = UUID.randomUUID().toString();


            //2.将token、refreshToken放到Redis中
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("uname", user.getUname());
            //以refreshToken作为key map作为value存放到redis中
            redisTemplate.opsForHash().putAll(refreshToken, map);
            //设置refreshToken过期时间
            redisTemplate.expire(refreshToken, JwtUtil.REFRESH_TOKEN_EXPIRE_TIME, TimeUnit.MILLISECONDS);

            //3.将token、refreshToken放到响应头里返回给游览器
            response.setHeader("authentication", token);
            response.setHeader("refresh", refreshToken);

            //4.向前端暴露自定义的响应头       Access-Control-Expose-Headers固定格式

            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.setHeader("Access-Control-Expose-Headers", "authentication,refresh");

            return new ResponseResult(200, ResultStatus.LOGIN_SUCCESS, "登陆成功", roleMenu);
        }else {
            return new ResponseResult(202, ResultStatus.NO_LOGIN, "用户不存在或密码错误", null);
        }
    }


    //鉴权方法
    @GetMapping("/hasperms/{account}/{perms}")
    public ResponseResult hasPerms(@PathVariable("account") String account,@PathVariable("perms") String perms){

        //通过账号查询所有得权限信息
        List<String> permsList= Arrays.asList(
                "user:all",
                "user:find",
                "user:update",
                "user:delete"
        );
        boolean result=permsList.contains(perms);
        ResponseResult responseResult=new ResponseResult();
        responseResult.setCode(200);


        if(result)
        {
            responseResult.setStatus(ResultStatus.HAVE_PERMS);
            responseResult.setMessage("有权限");
        }else {
            responseResult.setStatus(ResultStatus.NO_PERMS);
            responseResult.setMessage("没有权限");
        }
        return responseResult;
    }
}
